package net.zhengxinyun.performance.controller.login;

import com.sirdc.modules.core.exceptions.SystemException;
import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.Util.MD5;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.*;
import net.zhengxinyun.performance.service.exportService.ExportService;
import net.zhengxinyun.performance.service.indicators.CountryIndicatorsService;
import net.zhengxinyun.performance.service.indicators.CountryUnitIndicatorsService;
import net.zhengxinyun.performance.service.indicators.TownIndicatorsService;
import net.zhengxinyun.performance.service.login.LoginService;
import net.zhengxinyun.performance.service.login.RolePerService;
import net.zhengxinyun.performance.service.login.TokenService;
import net.zhengxinyun.performance.service.login.UserService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Results;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户管理页面
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private LoginService loginService;
    private TokenService tokenService;
    private UserService userService;

    @Autowired
    private ExportService exportService;

    @Autowired
    private RolePerService rolePerService;
    @Autowired
    private TownIndicatorsService townIndicatorsService;

    @Autowired
    private CountryIndicatorsService cityIndexService;

    @Autowired
    private CountryUnitIndicatorsService departIndexSercice;

    @Autowired
    public UserController(LoginService loginService, TokenService tokenService, UserService userService) {
        this.loginService = loginService;
        this.tokenService = tokenService;
        this.userService = userService;
    }

    @PostMapping("/insert")
    public Result<String> insert(@RequestBody UserParam param,HttpServletRequest request) throws Exception {
        UserFilter userFilter = new UserFilter();
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            userFilter.setUserName(param.userEntity.getUserName());
            List<UserFilter> query = userService.query(userFilter);
            if (ObjectUtils.isBlank(query)) {
                /*
                    保存用户
                 */
                String str = userService.saveUserInfo(param.userEntity, param.tokenEntity,request);
                if ("保存成功".equals(str)) {
                    return ResultUtils.getSuccessResults();
                }
            }
            return ResultUtils.getResults(Result.Status.ERROR, "添加失败，用户已存在");
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对");
    }

    @PostMapping("/update")
    public Result<String> update(@RequestBody UserParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            /*
                当前登录用户
             */
            UserEntity user = loginService.getUserByToken(param.tokenEntity);
            /*
                需要修改的用户
             */
            UserEntity userEntity = userService.getUseInfo(param.userEntity.getId());
            param.userEntity.setHaveRight(userEntity.getHaveRight());//先把原来的haveright赋值回去，避免被清空；

            int i ;
            try {

                /**
                 * 选择了角色 ，自定义框都清空
                 */
                if (ObjectUtils.isNotBlank(param.userEntity.getRoleid())) {
                    param.userEntity.setRoleRight(null);
                    param.userEntity.setBtnRight(null);
                    param.userEntity.setIndexRight(null);
                    //param.userEntity.setHaveRight(null);
                } else {   //选择了自定义 则角色失效 为空
                    /**
                     * 菜单权限
                     */
                    if (ObjectUtils.isNotBlank(param.userEntity.getCheckAllGroup())) {
                        List<String> rights = param.userEntity.getCheckAllGroup();
                        String roleRight = String.join(",", rights);
                        param.userEntity.setRoleRight(roleRight);
                        /**
                         * 拥有可操作的的菜单总量
                         */

                        //判断当前用户是否是超级管理员,设置可见菜单
                        if ("admin".equals(user.getUserPermissions())) {
                            param.userEntity.setHaveRight(roleRight);
                        }
                    }

                    /**
                     * 按钮权限
                     */
                    if (ObjectUtils.isNotBlank(param.userEntity.getBtnRights())) {
                        List<String> btnRights = param.userEntity.getBtnRights();
                        String StrBtnRight = String.join(",", btnRights);
                        param.userEntity.setBtnRight(StrBtnRight);
                    }

                    /**
                     * 指标权限
                     */
                    if (ObjectUtils.isNotBlank(param.userEntity.getCheckAllindexGroup())) {
                        List<String> indexList = param.userEntity.getCheckAllindexGroup();
                        String strIndex = String.join(",", indexList);
                        param.userEntity.setIndexRight(strIndex);

                        // param.rolePerEntity.setHaveIndexs(strIndex);
                    }

                      /*
                        市指标
                         */
                    String cityindex = null;
                    if (ObjectUtils.isNotBlank(param.userEntity.getCheckCityGroup())) {
                        List<String> indexList = param.userEntity.getCheckCityGroup();
                        cityindex = String.join(",", indexList);

                    }
                    param.userEntity.setCityIndex(cityindex);
                    /*
                     *单位指标
                     */
                    String departIndex = null;
                    if (ObjectUtils.isNotBlank(param.userEntity.getCheckUnitGroup())) {
                        List<String> indexList = param.userEntity.getCheckUnitGroup();
                        departIndex = String.join(",", indexList);

                    }
                    param.userEntity.setDepartIndex(departIndex);

                    param.userEntity.setRoleid(null);
                }

                /**
                 * 密码判断是否有修改过，修改过就重新加密。
                 */


                if (!userEntity.getUserPassword().trim().equals(param.userEntity.getUserPassword().trim())) {
                    String passWord = MD5.md5(param.userEntity.getUserPassword(), MD5.MD5_STR);
                    param.userEntity.setUserPassword(passWord);
                }

                /*
                    管理员修改自己的时候 不能修改到 是否管理员。
                 */
                if (user.getUserName().equals(userEntity.getUserName())) {
                    param.userEntity.setIsManger(userEntity.getIsManger());
                }


                i = userService.updateByPrimaryKeySelective(param.userEntity);
            } catch (Exception e) {
                return ResultUtils.getResults(Result.Status.ERROR, "修改失败，请重试");
            }
            if (i == 0) {
                return ResultUtils.getResults(Result.Status.ERROR, "修改失败，请重试");
            } else {
                return ResultUtils.getSuccessResults();
            }
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对");
    }

    @PostMapping("/delete")
    public Result<String> delete(@RequestBody UserParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {

            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
            if (userEntity.getUserName().equals(param.userEntity.getUserName())) {
                return ResultUtils.getResults(Result.Status.ERROR, "删除失败！！！您不能删除自己！！！");
            }


            int i = userService.delete(param.userEntity);
            if (i == 0) {
                return ResultUtils.getResults(Result.Status.ERROR, "删除失败，请重试");
            } else {
                return ResultUtils.getSuccessResults();
            }
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对");
    }


    @PostMapping("/query")
    public Result<HashMap<String, Object>> query(@RequestBody UserParam param, HttpServletRequest request) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
            UserFilter userfilter = new UserFilter();
            userfilter.setId(userEntity.getId());
            List<UserFilter> users = userService.queryUsers(userfilter);
            HashMap<String, Object> map = new HashMap<>();
            Double pageTotal = 1.0;

            if (!"admin".equals(userEntity.getUserPermissions())) {
                param.userFilter.setDepartcode(userEntity.getDepartcode());
            }
            if (StringUtils.isNotBlank(param.userFilter.getUserDepartment())) {
                //沙雕杰吧用户单位放在userdepartment字段上，还死都不改 需要特地转换一下
                param.userFilter.setDepartcode(param.userFilter.getUserDepartment());
            }

            List<UserFilter> list = userService.queryUsers(param.userFilter);
            if (list.size() == 0) {
                param.userFilter.setPageNumber(param.userFilter.getPageNumber() - 1);
                list = userService.queryUsers(param.userFilter);
            }


            for (UserFilter item : list) {

                RolePerEntity userRole = rolePerService.selectByPrimaryKey(item.getRoleid());
                String roleright, btnright, indexRight, cityIndex, departIndex;
                if (ObjectUtils.isBlank(userRole)) {
                    roleright = item.getRoleRight();
                    btnright = item.getBtnRight();
                    indexRight = item.getIndexRight();
                    cityIndex = item.getCityIndex();
                    departIndex = item.getDepartIndex();

                } else {
                    roleright = userRole.getRoleRight();
                    btnright = userRole.getBtnRight();
                    indexRight = userRole.getIndexRight();
                    departIndex = userRole.getDepartIndex();
                    cityIndex = userRole.getCityIndex();

                }

                /**
                 菜单勾选状态
                 */
                List<String> checks = Util.strToList(roleright);
                item.setCheckAllGroup(checks);
                /**
                 * 按钮权限
                 */
                List<String> btnChecks = Util.strToList(btnright);
                item.setBtnRights(btnChecks);

                /**
                 * 勾选的指标集合
                 */
                List<String> indexlist = Util.strToList(indexRight);
                item.setCheckAllindexGroup(indexlist);

                    /*
                        市对县指标集合
                     */
                List<String> cityIndexs = Util.strToList(cityIndex);
                item.setCheckCityGroup(cityIndexs);

                    /*
                        县直单位集合
                     */
                List<String> departindex = Util.strToList(departIndex);
                item.setCheckUnitGroup(departindex);

            }

            map.put("list", list);
            pageTotal = Util.intGetTotalPage(userService.queryForCount(param.userFilter), param.userFilter.getPageSize());
             /*else {
                List<UserEntity> list = new ArrayList<>();
                list.add(userEntity);
                map.put("list", list);
            }*/
            map.put("pageTotal", pageTotal);
            map.put("isManager", userEntity.getIsManger());
            map.put("departcode", userEntity.getDepartcode());
            /**
             *
             */

            /**
             * 角色菜单下拉框
             */
            RolePerFilter rolefilter = new RolePerFilter();
            if (!"admin".equals(userEntity.getUserPermissions())) {
                rolefilter.setDepartCode(userEntity.getDepartcode());
            }

            List<RolePerFilter> rolers = rolePerService.query(rolefilter);

            if (ObjectUtils.isNotBlank(userEntity.getRoleid()) && !"admin".equals(userEntity.getUserPermissions())) {
                RolePerFilter dto = new RolePerFilter();
                RolePerEntity role = rolePerService.selectByPrimaryKey(userEntity.getRoleid());
                dto.setId(role.getId());
                dto.setRole(role.getRole());
                rolers.add(dto);

            }
            map.put("roles", rolers);

            // map.put("btnaccess","query,del,upd");
            /**
             * --------可操作性的菜单数量-----
             */
            List<MenuLists> listRights = new ArrayList<>();
            RolePerEntity userRole = rolePerService.selectByPrimaryKey(userEntity.getRoleid());

            String strrights = "";
            if (ObjectUtils.isBlank(userRole)) {
                strrights = userEntity.getHaveRight();
            } else {
                strrights = userRole.getHaveRight();

            }
            if (StringUtils.isNotBlank(strrights)) {
                String[] menusarry = strrights.split(",");
                for (String codes : menusarry) {
                    MenuLists meun = rolePerService.getMenus(codes);
                    listRights.add(meun);
                }
            }
            map.put("haveRights", listRights);

            /**
             * ------------------获取可操作的---指标--集合----------
             */
            /**
             * 超级管理员
             */
            String year = (String) request.getSession().getAttribute("currentYear");
            if (year == null) {
                return ResultUtils.getResults(Result.Status.OVERTIME, "session过期", null);
            }

            if ("admin".equals(userEntity.getUserPermissions())) {
                /*
                县对乡镇指标
                 */
                System.out.println(year);
                TownIndicatorsFilter townfilter = new TownIndicatorsFilter();
                townfilter.setIndexType("二级指标");
                townfilter.setDateTime(year);
                List<TownIndicatorsFilter> listIndexs = townIndicatorsService.query(townfilter);
                map.put("indexRights", listIndexs);

                /*
                 *市指标
                 */
                CountryIndicatorsFilter cityfiler = new CountryIndicatorsFilter();
                cityfiler.setPageSize(0);
                // cityfiler.setLeadUnit(userEntity.getDepartcode());
                cityfiler.setDateTime(year);
                List<CountryIndicatorsFilter> cityIndexs = cityIndexService.query(cityfiler);
                map.put("cityIndex", cityIndexs);

                /*
                    县直单位指标
                 */
                CountryUnitIndicatorsFilter departFilter = new CountryUnitIndicatorsFilter();
                //departFilter.setLeadUnit(userEntity.getDepartcode());
                departFilter.setDateTime(year);
                departFilter.setPageSize(0);
                List<CountryUnitIndicatorsEntity> departIndex = departIndexSercice.query(departFilter, userEntity);
                map.put("departIndex", departIndex);

            } else {
                /**
                 * 非超管理员
                 */
                /*
                县对乡镇
                 */
                TownIndicatorsFilter townfilter = new TownIndicatorsFilter();
                townfilter.setPageSize(0);
                townfilter.setIndexType("二级指标");
                townfilter.setDateTime(year);
                if ("县直单位".equals(users.get(0).getDepartType())) {
                    townfilter.setLeadUnit(userEntity.getDepartcode());
                }
                List<TownIndicatorsFilter> listIndex = townIndicatorsService.query(townfilter);
                map.put("indexRights", listIndex);
                /*
                 *市指标
                 */
                CountryIndicatorsFilter cityfiler = new CountryIndicatorsFilter();
                cityfiler.setPageSize(0);
                cityfiler.setLeadUnit(userEntity.getDepartcode());
                cityfiler.setDateTime(year);
                List<CountryIndicatorsFilter> cityIndexs = cityIndexService.query(cityfiler);
                map.put("cityIndex", cityIndexs);

                 /*
                    县直单位指标
                 */
                CountryUnitIndicatorsFilter departFilter = new CountryUnitIndicatorsFilter();
                departFilter.setLeadUnit(userEntity.getDepartcode());
                departFilter.setDateTime(year);
                departFilter.setPageSize(0);
                List<CountryUnitIndicatorsEntity> departIndex = departIndexSercice.query(departFilter);
                map.put("departIndex", departIndex);

            }

            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    @PostMapping(value = "/loginLog")
    public Result<HashMap<String, Object>> loginLogList(@RequestBody UserParam userParam) {
//        Long id = userParam.userFilter.getId();

        List<LoginLog> loginLogList = userService.findByUserId(userParam.userFilter);

        HashMap<String, Object> map = new HashMap<>();

        Double pageTotal;
        if (userParam.userFilter.getPageNumber() == 0) {
            pageTotal = 1.0;
        }
        if (loginLogList.size() == 0) {
            userParam.userFilter.setPageNumber(userParam.userFilter.getPageNumber() - 1);
            loginLogList = userService.findByUserId(userParam.userFilter);
        }

        int jj = userService.queryForCountLog(userParam.userFilter);
        System.out.println(jj);
        pageTotal = Util.intGetTotalPage(userService.queryForCountLog(userParam.userFilter), userParam.userFilter.getPageSize());

        map.put("pageTotal", pageTotal);
        map.put("list", loginLogList);
        return ResultUtils.getSuccessResults(map);


    }

    /**
     * 请求自定义勾选数据
     *
     * @param param
     * @return
     */
    @PostMapping(value = "/getCheckValue")
    public Result<HashMap<String, Object>> getRoleRight(@RequestBody UserParam param) {
        HashMap<String, Object> map = new HashMap<>();
        Long roleid = param.userEntity.getRoleid();

        List<String> indexRight = new ArrayList<>();
        List<String> btnRight = new ArrayList<>();
        List<String> roleright = new ArrayList<>();
        List<String> cityIndex = new ArrayList<>();
        List<String> departIndex = new ArrayList<>();
        if (ObjectUtils.isNotBlank(roleid)) {
            RolePerEntity userRole = rolePerService.selectByPrimaryKey(roleid);
            indexRight = Util.strToList(userRole.getIndexRight());//县对乡镇指标
            btnRight = Util.strToList(userRole.getBtnRight());//按钮
            roleright = Util.strToList(userRole.getRoleRight());//菜单;
            cityIndex = Util.strToList(userRole.getCityIndex());
            departIndex = Util.strToList(userRole.getDepartIndex());
        }
        map.put("checkUnitGroup", departIndex);//县直单位指标
        map.put("checkCityGroup", cityIndex);//市对县
        map.put("checkAllindexGroup", indexRight);//县对乡镇
        map.put("btnRight", btnRight);
        map.put("roleRight", roleright);
        return ResultUtils.getSuccessResults(map);
    }


    /**
     * @param param
     */
    @PostMapping(value = "/checkUserIsExist")
    public Result<HashMap<String, Object>> checkUserIsExist(@RequestBody UserParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            boolean flag = userService.checkUserIsExist(param.userFilter.getUserName());
            HashMap<String, Object> map = new HashMap<>();
            if (!flag) {
                map.put("success", false);
                map.put("msg", "用户校验失败，该用户已经存在，请重试");
                return ResultUtils.getSuccessResults(map);
            } else {
                map.put("success", true);
                map.put("msg", "用户校验成功！");
                return ResultUtils.getSuccessResults(map);
            }
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    /*
        导出用户
     */
    @GetMapping("/exportUser")
    public void exportUsers(HttpServletResponse response, String departcode) {
        if ("1092".equals(departcode)) {
            departcode = null;
        }

        HSSFWorkbook wb = exportService.exportUsers(departcode);
        HSSFSheet sheet = wb.getSheetAt(0);
        int rownum = sheet.getLastRowNum();
        if (rownum == 0) {
            throw new SystemException("没有数据");
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            String filename = "用户情况.xls";
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            wb.write(out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    /**
     * 导入 excel 批量修改用户
     *
     * @param param
     */
    @PostMapping("/batchImportUser")
    public Result<HashMap<String, List<String>>> importUsers(@RequestBody UserParam param) {
        List<UserFilter> list = param.userEntity.getListUser();

        HashMap<String, List<String>> map = userService.batchUpdateUser(list, param.userEntity.getCheckCode());
        List<String> errlist = map.get("error");
        List<String> warinlist = map.get("warn");
        String msg = "校验成功，错误" + errlist.size() + " , 警告" + warinlist.size() + "";
        if ("0".equals(param.userEntity.getCheckCode())) {
            return ResultUtils.getResults("200", msg, map);
        } else {
            return ResultUtils.getResults("200", "更新成功", null);
        }

    }

    /**
     * 批量修改用户权限
     * @param param
     * @return
     */
    @PostMapping("/batchUpdateRight")
    public Result batchUpdateRight(@RequestBody UserParam param)
    {
        UserEntity loiginUser = loginService.getUserByToken(param.tokenEntity);
        List<Long> ids  = param.userFilter.getIds();
        if(ObjectUtils.isBlank(ids))
        {
            return ResultUtils.getResults("500","您未选择要修改的用户");
        }
        for(Long id:ids)
        {
          UserEntity userEntity= userService.updateRight(id,param.userFilter);
          if("admin".equals(loiginUser.getUserPermissions()))
          {
              userEntity.setHaveRight( userEntity.getRoleRight() );
          }
         int i = userService.updateByPrimaryKeySelective(userEntity);
          if(i ==0)
          {

          }
        }
        return ResultUtils.getSuccessResults();
    }

    /**
     * 批量修改用户角色
     * @param param
     * @return
     */
    @PostMapping("/batchUpdRole")
    public Result batchUpdateRole(@RequestBody UserParam param)
    {
        UserEntity loiginUser = loginService.getUserByToken(param.tokenEntity);
        Long roleId = param.userFilter.getRoleid();
        List<Long> ids = param.userFilter.getIds();
        if(ObjectUtils.isBlank(ids))
        {
            ResultUtils.getResults(Result.Status.ERROR,"请先选择用户");
        }

        for (Long id:ids)
        {
            UserEntity  userEntity = userService.selectUserByPrimaryKey(id);
            userEntity.setRoleid(roleId);
            userService.updateByPrimaryKeySelective(userEntity);
        }

        return ResultUtils.getSuccessResults();

    }


}

class UserParam {
    public TokenEntity tokenEntity;
    public UserEntity userEntity;
    public UserFilter userFilter;
}
